import React, { useState, useEffect } from 'react';
import { connect } from 'dva';
import EditTemplate from '@/components/EditTemplate';

type Notice = {
  title: '标题';
  content?: '内容区域';
};

const urlList = [
  {
    create: '/api/article/v1/notification/create',
    update: '/api/article/v1/update',
  },
  { create: '/api/article/v1/law/create', update: '/api/article/v1/update' },
];

const BuildEdit = ({ location, dispatch }: any) => {
  const [detail, setDetail]: [Notice | null, Function] = useState(null);
  const { id, type } = location.query;

  const saveUrl = id ? urlList[type].update : urlList[type].create;
  useEffect(() => {
    setDetail({});

    if (id) {
      dispatch({
        type: '$request/post',
        payload: {
          url: type == 1 ? '/api/article/v1/detail' : '/api/article/v1/detail',
          data: {
            uuid: id,
          },
        },
      }).then(res => {
        setDetail(res);
      });
    }
  }, []);
  const filters = [
    {
      title: '基础信息',
      list: [
        {
          key: 'title',
          type: 'input',
          label: '标题',
          placeholder: '请输入标题',
          rules: [{ required: true }],
          span: 24,
        },
        {
          key: 'content',
          type: 'ueditor',
          label: '内容',
          span: 24,
        },
        {
          key: 'fileList',
          type: 'upload',
          label: '附件',
          span: 24,
        },
      ],
    },
  ];
  const preproccess = data => {
    const fileUuidList = data.fileList
      ? data.fileList.map(item => item.uuid)
      : [];
    return {
      fileUuidList,
      ...data,
    };
  };
  return (
    <div>
      <EditTemplate
        filters={filters}
        initialValues={detail}
        preproccess={preproccess}
        updateUrl={saveUrl}
        formLayout={{
          labelCol: { span: 6 },
        }}
      />
    </div>
  );
};

export default connect((state: any) => state.auth)(BuildEdit);
